<html>
<head>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <script src="//ajax.aspnetcdn.com/ajax/jQuery/jquery-1.11.1.min.js"></script>
  <script type="text/javascript" src="js/client.js"></script>
  <script type="text/javascript" src="js/board.js"></script>
</head>

<body>
  <table>
    <tr>
      <td style="width: 150px"><span id='name'></span></td>
      <td style="width: 50px"><span id='role'></span><span id='current' style="display:none">(turn)</span></td>
      <td><button id='ready'>ready</button></td>
    </tr>
    <tr>
      <td colspan="3"><span id='result'></span></td>
    </tr>
  </table>
  <div id="game"></div>
<script type="text/javascript">

  var dfd = $.Deferred();
  var role = null;
  var turn = false;
  var board = '';
  
  var blackwhite = _client.create_service('blackwhite');
  _client.onconnect = function() {
    dfd.resolve();
  }
  _client.connect(); 
  
  blackwhite._handle_role_update = function(data) {
    $(data.players).each(function(index, player){
      if(player.id == _client.id) {
        role = player.role;

        $('#role').text(player.role)
        $('#ready').text(player.state)
        if (player.state == 'playing') {
          $('#ready').attr('disabled', true);
          _client.invoke('blackwhite_refresh');
        } else {
          $('#ready').attr('disabled', false);
        }
        
        return false;
      }
    });
  };
  
  blackwhite._handle_blackwhite = function(data) {
    board = data.board;
    if (data.current == role) {
      turn = true;
      $('#current').show();
    } else {
      turn = false;
      $('#current').hide();
    }
    _chessboard.draw(data.board, data.last_move, turn);
    var bCount = 64 - data.board.replace(/b/g,'').length;
    var wCount = 64 - data.board.replace(/w/g,'').length;
    $('#result').text('black ' + bCount + ' vs white ' + wCount);
  }
  
  $('#ready').on('click', function(){
     $('#ready').attr('disabled', true);
     if($('#ready').text() == 'preparing') {
       _client.invoke('state_ready');
     } else if ($('#ready').text() == 'ready') {
       _client.invoke('state_unready');
     }
  });
  
  dfd.then(function(){
    var id = document.location.hash;
    if (id.length == 0) {
      id = 'default'
    }
    return blackwhite.enter_room(id);
  }).then(function(){
    $('#name').text(_client.name);
    _chessboard.init($('#game'), 300);
    _chessboard.onclick = function(x, y) {
      if(turn) {
        if(board.charAt(y*8+x) == 'x') {
          _client.invoke('blackwhite_move', {x:x,y:y});
        }
      }
    }
  }).then(function(){
    return _client.invoke('role_get_states');
  }).fail(function(msg){
    console.log('Error:', msg);
  });
  
</script>
</body>
</html>
